package com.hxd.common.core.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.hxd.common.exception.TxException;

@Component
public class TxManager {

	@Autowired
	private PlatformTransactionManager txManager;
	
	public boolean exec(IWork work) {
		boolean res = false;
		TransactionStatus status = txManager.getTransaction(new DefaultTransactionDefinition());
		try {
			res = work.run();
			if(res)
				txManager.commit(status);
			else
				throw new TxException();
		} catch (Exception e) {
			txManager.rollback(status);
		}
		return res;
	}
}
